package com.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.net.UnknownHostException;
import java.util.Objects;

public class HttpUtil {
    public static JSONObject post(String url, Object param) throws Exception {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody reqBody = RequestBody.create(mediaType, JSON.toJSONString(param));
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", reqBody)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response res = client.newCall(request).execute();
            int code = res.code();
            if (code != 200) {
                throw new RuntimeException(code + res.message());
            }
            ResponseBody resBody = res.body();
            if (resBody == null) {
                return null;
            }
            String resStr = resBody.string();
            JSONObject jsonObject = JSONObject.parseObject(resStr);

            if (!"0".equals(jsonObject.getString("code"))) {
                throw new RuntimeException(jsonObject.getString("message"));
            }

            return jsonObject;
        } catch (UnknownHostException unknownHostException) {
            throw new RuntimeException("请检查服务器地址及网络状况-" + unknownHostException.getMessage());
        }
    }

    public static JSONObject get(String url) throws Exception {
        try {
            Request request = new Request.Builder().url(url).get().build();
            OkHttpClient okHttpClient = new OkHttpClient();
            Response res = okHttpClient.newCall(request).execute();
            String resStr = Objects.requireNonNull(res.body()).string();
            JSONObject resJSONObject = JSONObject.parseObject(resStr);
            if (!resJSONObject.getBoolean("success")) {
                throw new Exception(resJSONObject.getString("message"));
            }
            return resJSONObject;
        } catch (UnknownHostException unknownHostException) {
            throw new Exception("请检查服务器地址及网络状况-" + unknownHostException.getMessage());
        }
    }
}
